package com.lcz.manage.util.event.publisher.impl;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import com.lcz.manage.util.event.publisher.enums.PublisherType;
import com.lcz.manage.util.event.publisher.factory.EventPublisherFactory;

import lombok.extern.slf4j.Slf4j;

/**
 * 异步事件发送器
 *
 * @author xingyongjiang@yunrong.cn
 * @version V3.0
 * @since 2021/4/19 13:08
 */

@Slf4j
@Component
public class ThreadPoolAsyncApplicationEventPublisher extends AbstractEventPublisher {

    private ThreadPoolTaskExecutor taskExecutor = null;

    @Autowired
    private EventPublisherFactory eventPublisherFactory;

    @PostConstruct
    public void init() {
        //线程池初始化
        taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(2);
        taskExecutor.setMaxPoolSize(8);
        taskExecutor.setQueueCapacity(64);
        taskExecutor.setAllowCoreThreadTimeOut(true);
        taskExecutor.setKeepAliveSeconds(3000);
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        taskExecutor.setThreadNamePrefix("collection_common_async_event_threadPool");
        taskExecutor.initialize();

        //注册
        eventPublisherFactory.register(PublisherType.THREAD_POLL_ASYNC.getCode(), this);
    }

    @Override
    protected Executor getExecutor() {
        return this.taskExecutor;
    }
}
